﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using DHAA.Areas.Administrator.Models;
using DHAA.Global;

namespace DHAA.Areas.Administrator.Controllers
{
    public class ProductController : Controller
    {
        private     SqlConnection       sqlConnection;
        readonly    GlobalController    globalController = new GlobalController();
        private     SqlCommand          sqlCommand;
        private     SqlDataAdapter      sqlDataAdapter;
        //  private DataSet dataSet;
        private     ProductModels       productModels;
        private     int count;

        public static string Short(string text, int chopLength)
        {
            const string postfix = "...";
            if (text == null || text.Length < chopLength)
        return text;
    else
        return text.Substring(0, chopLength- postfix.Length) + postfix;
        }

        private List<ProductModels> SelectAllProducts()
        {
            sqlConnection = globalController.getConnection();
          
            sqlDataAdapter = new SqlDataAdapter("SelectAllProduct", sqlConnection){SelectCommand = {CommandType = CommandType.StoredProcedure}};
            DataSet ds = new DataSet();
            sqlDataAdapter.Fill(ds);
            DataTable dt = ds.Tables[0];



            var proList = new List<ProductModels>();


            foreach (DataRow r in dt.Rows)
            {
                string Description = r.Field<string>("Description");
                string striptags = Regex.Replace(Description, @"<(.|\n)*?>", string.Empty);
                string shortDescription = Short(striptags, 100);
                
                productModels = new ProductModels
                {
                    ProductID = r.Field<int>("ProductID"),
                    ProductName = r.Field<string>("ProductName"),
                    ProductImage = r.Field<string>("ProductImage"),
                    Price = r.Field<double>("Price"),
                    CategoryID = r.Field<int>("CategoryID"),
                    CategoryName=r.Field<string>("CategoryName") ,
                    Description = shortDescription,
                    FeedBackID = r.Field<int?>("FeedBackID")
                   
                };
                proList.Add(productModels);
            }
            return proList;


        }


        private ProductModels SelectProductByID(int id)
        {
            sqlConnection = globalController.getConnection();

            sqlDataAdapter = new SqlDataAdapter("SelectProductByID", sqlConnection) { SelectCommand = { CommandType = CommandType.StoredProcedure } };
            SqlParameter pr = new SqlParameter("@ProductID", id);
            sqlDataAdapter.SelectCommand.Parameters.Add(pr);
            DataSet ds = new DataSet();
            sqlDataAdapter.Fill(ds);
         



            DataRow r = ds.Tables[0].Rows[0];
                productModels = new ProductModels
                {
                    ProductID = r.Field<int>("ProductID"),
                    ProductName = r.Field<string>("ProductName"),
                    ProductImage = r.Field<string>("ProductImage"),
                    Price = r.Field<double>("Price"),
                    CategoryID = r.Field<int>("CategoryID"),
                    CategoryName = r.Field<string>("CategoryName"),
                    Description = r.Field<string>("Description"),
                    FeedBackID = r.Field<int?>("FeedBackID")

                };
               
    return productModels;
            
        }


        private  List<ProductModels> SelectProductByCategoryID(int catID)
        {
            sqlConnection = globalController.getConnection();

            sqlDataAdapter = new SqlDataAdapter("SelectProductByCategoryID", sqlConnection) { SelectCommand = { CommandType = CommandType.StoredProcedure } };
            SqlParameter pr = new SqlParameter("@CategoryID", catID);
            sqlDataAdapter.SelectCommand.Parameters.Add(pr);

            DataSet ds = new DataSet();
            sqlDataAdapter.Fill(ds);
            DataTable dt = ds.Tables[0];



            var proList = new List<ProductModels>();


            foreach (DataRow r in dt.Rows)
            {
                string Description = r.Field<string>("Description");
                string striptags = Regex.Replace(Description, @"<(.|\n)*?>", string.Empty);
                string shortDescription = Short(striptags, 100);

                productModels = new ProductModels
                {
                    ProductID = r.Field<int>("ProductID"),
                    ProductName = r.Field<string>("ProductName"),
                    ProductImage = r.Field<string>("ProductImage"),
                    Price = r.Field<double>("Price"),
                    CategoryID = r.Field<int>("CategoryID"),
                    CategoryName = r.Field<string>("CategoryName"),
                    Description = shortDescription,
                    FeedBackID = r.Field<int?>("FeedBackID")

                };
                proList.Add(productModels);
            }
            return proList;
        }


        //
        // GET: /Administrator/Producnt/

        public ActionResult Index()
        {
            List<ProductModels> ilist = SelectAllProducts();
            return View(ilist);
        }

        public  ActionResult List(int id)
        {
            List<ProductModels> catalist = SelectProductByCategoryID(id);
            return PartialView("List",catalist);
        }



        //
        // GET: /Administrator/Producnt/Details/5

        public ActionResult Details(int id)
        {
            ProductModels model = SelectProductByID(id);
            return View(model);
        }

        //
        // GET: /Administrator/Producnt/Create

        public ActionResult Create(int id)
        {
            ProductModels prd = new ProductModels() {CategoryID = id};
            return View(prd);
        } 

        //
        // POST: /Administrator/Producnt/Create

        [HttpPost]
        public ActionResult Create(ProductModels model)
        {
            try{
               sqlConnection = globalController.getConnection();
                sqlCommand = new SqlCommand("InsertProduct", sqlConnection){ CommandType = CommandType.StoredProcedure };
                var pr = new[]
                                      {
                                          new SqlParameter("@CategoryID", model.CategoryID), 
                                          new SqlParameter("@ProductName", model.ProductName), 
                                          new SqlParameter("@ProductImage", model.ProductImage), 
                                          new SqlParameter("@Description", model.Description), 
                                          new SqlParameter("@Price", model.Price),
                                          new SqlParameter("@FeedBackID", SqlDbType.Int)
                                              {
                                                  Value = 0
                                              }
                                        
                                      };
                sqlCommand.Parameters.AddRange(pr);
                sqlCommand.ExecuteNonQuery();
                ViewData["MessageSuccess"] = "Create successfull";
                return View(model);
            }
            catch(SqlException se)
            {
                ViewData["MessageError"] = se.Message;
                return View();
            }
        }
        
        //
        // GET: /Administrator/Producnt/Edit/5
 
        public ActionResult Edit(int id)
        {
            ProductModels prd = SelectProductByID(id);
            return View(prd);
        }

        //
        // POST: /Administrator/Producnt/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, ProductModels model)
        {
            try
            {
                if (model.FeedBackID == null) model.FeedBackID = 0;

                sqlConnection = globalController.getConnection();
                sqlCommand = new SqlCommand("UpdateProduct", sqlConnection) { CommandType = CommandType.StoredProcedure };
                var pr = new[]
                                      {
                                         new SqlParameter("@ProductID", id), 
                                          new SqlParameter("@CategoryID", model.CategoryID), 
                                          new SqlParameter("@ProductName", model.ProductName), 
                                          new SqlParameter("@ProductImage", model.ProductImage), 
                                          new SqlParameter("@Description", model.Description), 
                                          new SqlParameter("@Price", model.Price),
                                          };
                sqlCommand.Parameters.AddRange(pr);
                sqlCommand.ExecuteNonQuery();
                ViewData["MessageSuccess"] = "Update category successful";
                return View(model);
            }
            catch (SqlException se)
            {
                ViewData["MessageError"] = se.Message;
                return View();
            }
        }

        //
        // GET: /Administrator/Producnt/Delete/5
 
        public ActionResult Delete(int id)


        {
            ProductModels prd = SelectProductByID(id);
            return View(prd);
        }

        //
        // POST: /Administrator/Producnt/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {

                sqlConnection = globalController.getConnection();
                sqlCommand = new SqlCommand("DELETE FROM Products Where ProductID="+id, sqlConnection);
               sqlCommand.ExecuteNonQuery();
                ViewData["MessageSuccess"] = "Deleted successful";
                return PartialView("Message");
            }
            catch (SqlException se)
            {
                ViewData["MessageError"] = se.Message;
                return View();
            }
        }
    }
}
